package org.swingDemo.UI;

import com.esotericsoftware.tablelayout.swing.Table;
import org.swingDemo.helper.StringHelper;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowEvent;

public class CommandPanel extends JPanel {

    private JProgressBar progressBar;
    private JLabel progressLabel;
    private JButton startStopButton;
    private JButton closeButton;

    private int fileCount;
    private int fileIndex;

    public CommandPanel() {
        super(new BorderLayout());
        initPanel();
    }

    public void showProgressComponents() {
        progressBar.setVisible(true);
        progressLabel.setVisible(true);
    }

    public void hideProgressComponents() {
        progressBar.setVisible(false);
        progressLabel.setVisible(false);
    }

    public void setFileCount(int fileCount) {
        this.fileCount = fileCount;
        updateProgressInfo();
    }

    public void setFileIndex(int fileIndex) {
        this.fileIndex = fileIndex;
        updateProgressInfo();
    }

    public void updateProgressInfo() {
        if (fileCount != 0) {
            progressBar.setValue((int)(fileIndex / fileCount * 100));
            progressLabel.setText(fileIndex + "/" + fileCount);
        }
    }

    public void handleFileClassifyWorkerDone() {
        hideProgressComponents();
        startStopButton.setText(StringHelper.START);
    }

    private void initPanel() {
        progressBar = new JProgressBar(0, 100);
        progressBar.setIndeterminate(true);
        progressLabel = new JLabel("");

        Table progressTable = new Table();
        progressTable.defaults().pad(20);
        progressTable.addCell(progressBar).expandX().fillX();
        progressTable.addCell(progressLabel);

        startStopButton = new JButton(StringHelper.START);
        startStopButton.addActionListener(l -> {
            handleStartStopCommand();
        });

        closeButton = new JButton(StringHelper.CLOSE);
        closeButton.addActionListener(l -> {
            handleCloseCommand();
        });

        Table commandTable = new Table();
        commandTable.addCell(startStopButton);
        commandTable.addCell(closeButton);

        this.add(progressTable, BorderLayout.NORTH);
        this.add(commandTable, BorderLayout.CENTER);

        hideProgressComponents();
    }

    private void handleStartStopCommand() {
        if (StringHelper.START.equals(startStopButton.getText())) {
            if (MainFrame.mainFrame.startFileClassifyWorker()) {
                showProgressComponents();
                startStopButton.setText(StringHelper.STOP);
            }
        } else {
            MainFrame.mainFrame.stopFileClassifyWorker();
            hideProgressComponents();
            startStopButton.setText(StringHelper.START);
        }
    }

    private void handleCloseCommand() {
        MainFrame.mainFrame.dispatchEvent(new WindowEvent(MainFrame.mainFrame, WindowEvent.WINDOW_CLOSING));
    }
}
